package com.wcj.springboot.controller;

import cn.hutool.core.io.FileUtil;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcj.springboot.common.Result;
import com.wcj.springboot.entity.Files;
import com.wcj.springboot.entity.User;
import com.wcj.springboot.mapper.FileMapper;
import com.wcj.springboot.service.IFileService;
import com.wcj.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Jue
 */
@RestController
@RequestMapping("/file")
public class FileController{

    @Resource
    private FileMapper fileMapper;

    @Resource
    private IFileService fileService;

    @PostMapping("/updateEnable")
    public Result updateEnable(@RequestBody Files files){
        return Result.success(fileService.updateById(files));
    }

    @DeleteMapping("/{id}")
    public Result removeById(@PathVariable Integer id){
        Files files = fileService.getById(id);
        files.setIsDelete(true);
        fileService.updateById(files);
        return Result.success();
    }


    @PostMapping("/del/batch")
    public Result removeBatchByIds(@RequestBody List<Integer> ids){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        List<Files> files = fileService.list(queryWrapper);
        for(Files file : files){
            file.setIsDelete(true);
            fileService.updateById(file);
        }
        return Result.success();
    }


    @GetMapping("/page")
    public Result getPage(@RequestParam Integer pageNum,
                          @RequestParam Integer pageSize,
                          @RequestParam(defaultValue = "") String name){
        IPage<Files> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",false);
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        return Result.success(fileService.page(page,queryWrapper));
    }


    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT+type;

        File uploadFile = new File(fileUploadPath+fileUUID);
        if(!uploadFile.getParentFile().exists()){
            uploadFile.getParentFile().mkdirs();
        }

        String url;
        file.transferTo(uploadFile);
        String md5 = SecureUtil.md5(uploadFile);

        QueryWrapper<Files> query = new QueryWrapper<>();
        query.eq("md5",md5);
        Files files;
        if(fileMapper.selectList(query).size() == 0){
            url = "http://localhost:9090/file/"+fileUUID;
        }else{
            url = fileMapper.selectList(query).get(0).getUrl();
            uploadFile.delete();
        }


        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);

        return Result.success(url);
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException{
        File uploadFile = new File(fileUploadPath+fileUUID);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }



}